package com.lpf.json.serializable;

import cn.hutool.core.collection.ListUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.lpf.json.serializable.vo.McTerminalVo;
import org.springframework.boot.jackson.JsonComponent;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@JsonComponent
public class JacksonConfiguration02 {

    private static final List<String> exclude = ListUtil.toList("serialVersionUID");
    private static final Map<String, String> toNewName;

    static {
        toNewName = new HashMap<>();
        toNewName.put("msg", "message");
    }

    public static class DateFormatSerializer extends JsonSerializer<McTerminalVo> {
        @Override
        public void serialize(McTerminalVo r, JsonGenerator generator, SerializerProvider serializers) throws IOException {
            try {
                generator.writeStartObject();

                Field[] fields = r.getClass().getDeclaredFields();

                for (Field field : fields) {
                    field.setAccessible(true);
                    String name = field.getName();
                    Object value = field.get(r);

                    // 不需要输出的字段
                    if (exclude.contains(name)) {
                        continue;
                    }

                    // 换个新的名称
                    String newName = toNewName.getOrDefault(name, name);
                    generator.writeObjectField(newName, value);
                }

                generator.writeEndObject();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    public static class DateParseDeserializer extends JsonDeserializer<McTerminalVo> {
        @Override
        public McTerminalVo deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
            System.out.println("----------------------");
            String valueAsString = p.getValueAsString();
            return null;
        }
    }
}
